package com.dlut.blob;

import com.dlut.bean.Customer;
import com.dlut3.util.JDBCUtil;
import org.junit.jupiter.api.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;

public class BlobTest {

    /**
     * 查询 Blob 类型
     * @throws Exception 异常
     */
    @Test
    public void test1() throws Exception {
        Connection conn = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            conn = JDBCUtil.getConnection();
            String sql = "select id,name,email,birth,photo from customers where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setObject(1,22);

            rs = ps.executeQuery();

            if (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");
                String email = rs.getString("email");
                Date birth = rs.getDate("birth");

                Customer customer = new Customer(id, name, email, birth);
                System.out.println(customer);

                Blob photo = rs.getBlob("photo");
                is = photo.getBinaryStream();
                fos = new FileOutputStream("chenghaoxun.jpg");
                byte[] buffer = new byte[1024];
                int len;
                while ((len = is.read(buffer)) != -1){
                    fos.write(buffer,0,len);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            JDBCUtil.closeResource(conn,ps,rs);
        }
    }

    /**
     * 向表中插入 Blob类型的字段
     * @throws Exception 异常
     */
    @Test
    public void test() throws Exception {
        Connection conn = JDBCUtil.getConnection();
        String sql = "insert into customers(name,email,birth,photo) values(?,?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);

        ps.setObject(1, "陈皓勋");
        ps.setObject(2,"837215@ydgiu.com");
        ps.setObject(3,"2000-01-03");

        FileInputStream fis = new FileInputStream("123456.jpg");
        ps.setBlob(4,fis);

        ps.execute();

        JDBCUtil.closeResource(conn,ps);
    }
}
